package org.yuanqiframework.yuanqi.web.auth;

import lombok.Getter;
import org.yuanqiframework.yuanqi.core.utils.StringUtils;
import org.yuanqiframework.yuanqi.web.auth.entity.LoginDTO;

import java.util.Map;
import java.util.Set;

@Getter
public class AuthContext {

    private LoginDTO loginDTO = new LoginDTO();

    private static ThreadLocal<AuthContext> authContextThreadLocal = new ThreadLocal<>();

    public AuthContext(LoginDTO loginDTO) {
        if (loginDTO != null) {
            this.loginDTO = loginDTO;
        }
        setAuthContext(this);
    }

    public static AuthContext getAuthContext() {
        return authContextThreadLocal.get();
    }

    private static void setAuthContext(AuthContext authContext) {
        authContextThreadLocal.set(authContext);
    }

    public static void clearAuthContext() {
        authContextThreadLocal.remove();
    }


    public static Map<String, Object> getInfoMap() {
        AuthContext authContext = authContextThreadLocal.get();
        LoginDTO loginDTO = authContext.loginDTO;
        return loginDTO.getInfoMap();
    }

    public static Set<String> getRoles() {
        AuthContext authContext = authContextThreadLocal.get();
        LoginDTO loginDTO = authContext.loginDTO;
        return loginDTO.getRoles();
    }

    public static String getUserId() {
        AuthContext authContext = authContextThreadLocal.get();
        LoginDTO loginDTO = authContext.loginDTO;
        if (loginDTO == null) {
            return null;
        }
        return loginDTO.getUserId();
    }


    public static boolean isLogin() {
        AuthContext authContext = authContextThreadLocal.get();
        LoginDTO loginDTO = authContext.loginDTO;
        if (loginDTO != null) {
            String token = loginDTO.getToken();
            return StringUtils.isNotEmpty(token);
        }
        return false;
    }


    @Override
    public String toString() {
        return "AuthContext{" + "loginDTO=" + loginDTO + '}';
    }
}
